<template>
  <div class="rule-details">
    <div class="rule-details__preview">
      <Preview
        :visitor-notice="visitorNotice"
        :visitor-rules="visitorRules"
      />
    </div>
    <div class="rule-details__fill">
      <div class="button-group card">
        <div class="button-group__box">
          <div
            class="button button--plain"
            @click="addRule(1)"
          >
            <i class="el-icon-plus icon" />
            添加须知
          </div>

          <div
            class="button button--plain"
            @click="addRule(2)"
          >
            <i class="el-icon-plus icon" />
            详细规则
          </div>
        </div>
        <div class="button-group__box">
          <div
            v-if="formData.ruleId"
            class="button button--plain"
            @click="back"
          >
            取消修改
          </div>
          <div
            class="button button--primary"
            @click="submitEvent"
          >
            <i v-if="loading" class="el-icon-loading" />
            {{ formData.ruleId ? '保存修改' : '提交数据' }}
          </div>
        </div>
      </div>

      <div class="content-warp">
        <div class="card">
          <div class="title">访客须知</div>
          <el-form
            ref="noticeFormRef"
            :model="formData.noticeForm"
            label-width="auto"
          >
            <div
              v-for="(item, index) in formData.noticeForm.content"
              :key="`content-${index}`"
              class="form-item__box"
            >
              <i
                class="close-icon el-icon-close"
                @click="deleteRule('noticeForm', index)"
              />
              <el-form-item
                :prop="`content.${index}.icon`"
                :rules="{
                  required: true,
                  message: '图标不能为空',
                  trigger: ['blur', 'change'],
                }"
              >
                <template #label>
                  <span class="form-label">访客须知图标-{{ index + 1 }}</span>
                </template>
                <Upload
                  :file-list="formData.noticeForm.content[index].icon"
                  :on-success="(e) => uploadIconSuccess(e, index)"
                />
              </el-form-item>
              <el-form-item
                :prop="`content.${index}.content`"
                :rules="{
                  required: true,
                  message: '须知内容不能为空',
                  trigger: ['blur', 'change'],
                }"
              >
                <template #label>
                  <span class="form-label">访客须知内容-{{ index + 1 }}</span>
                </template>
                <el-input
                  v-model="formData.noticeForm.content[index].content"
                  type="textarea"
                  autosize
                  placeholder="请填写规则详情内容"
                />
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="card">
          <div class="title">规则详情</div>
          <el-form
            ref="ruleDetailsFormRef"
            :model="formData.ruleDetailsForm"
          >
            <div
              v-for="(item, index) in formData.ruleDetailsForm.content"
              :key="`ruleDetails-${index}`"
              class="form-item__box"
            >
              <i
                class="close-icon el-icon-close"
                @click="deleteRule('ruleDetailsForm', index)"
              />
              <el-form-item
                :prop="`content.${index}.content`"
                :rules="{
                  required: true,
                  message: '规则详情不能为空',
                  trigger: ['blur', 'change'],
                }"
              >
                <template #label>
                  <span class="form-label">规则详情内容-{{ index + 1 }}</span>
                </template>
                <el-input
                  v-model="formData.ruleDetailsForm.content[index].content"
                  type="textarea"
                  :autosize="{ minRows: 2 }"
                  placeholder="请填写规则详情内容"
                  :maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Preview from '@/views/visitRule/components/Preview.vue'
import Upload from '@/views/visitRule/components/Upload.vue'
import { editVisitorRule, getVisitorRuleList, setVisitorRule } from '@/api/v2/visitor'
export default {
  name: '',
  components: {
    Preview,
    Upload
  },
  data() {
    return {
      formData: {
        ruleId: null,
        noticeForm: {
          content: [{ icon: '', content: '' }]
        },
        ruleDetailsForm: {
          content: [{ content: '' }]
        }
      },
      loadProgress: 0,
      loading: false
    }
  },
  computed: {
    visitorNotice() {
      return this.formData.noticeForm.content
    },
    visitorRules() {
      return this.formData.ruleDetailsForm.content
    },
    noticeLen() {
      return this.formData.noticeForm.content.length
    },
    ruleDetailsLen() {
      return this.formData.ruleDetailsForm.content.length
    }
  },
  created() {
    const { query } = this.$route
    this.formData.ruleId = query?.ruleId
    if (query?.ruleId) {
      this.getRuleDetails()
    }
  },
  methods: {
    addRule(addType) {
      const type = {
        1: { icon: '', content: '' },
        2: { content: '' }
      }
      if (addType === 1) {
        if (this.noticeLen >= 5) return this.$message.error('访客须知最多只能添加五条')
        this.formData.noticeForm.content.push(type[addType])
      } else {
        if (this.ruleDetailsLen >= 3) return this.$message.error('规则详情最多只能添加三条')
        this.formData.ruleDetailsForm.content.push(type[addType])
      }
    },
    uploadIconSuccess(e, index) {
      this.formData.noticeForm.content[index].icon = e.data.path
      this.validateField(`content.${index}.icon`)
    },
    validateField(field) {
      this.$refs.noticeFormRef.validateField(field)
    },
    onProgress(e) {
      this.loadProgress = parseInt(e.percent)
    },

    async submitEvent() {
      const noticeValid = await this.validateNoticeForm()
      const ruleDetailsValid = await this.validateRuleDetailsForm()
      if (!noticeValid || !ruleDetailsValid) return this.$message.error('请将信息填写完整！')
      const params = this.paramsFormatter()
      if (!this.formData.ruleId) {
        await this.createVisitorRule(params)
      } else {
        await this.editeVisitorRule(params)
      }
    },

    validateNoticeForm() {
      return new Promise(resolve => {
        this.$refs.noticeFormRef.validate(flag => {
          resolve(flag)
        })
      })
    },
    validateRuleDetailsForm() {
      return new Promise(resolve => {
        this.$refs.ruleDetailsFormRef.validate(flag => {
          resolve(flag)
        })
      })
    },

    deleteRule(type, index) {
      this.$confirm('是否删除该项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData[type].content.splice(index, 1)
      })
    },

    async createVisitorRule(data) {
      this.loading = true
      try {
        const res = await setVisitorRule(data)
        this.$message.success('创建成功')
        setTimeout(() => {
          this.back()
        }, 1000)
      } catch (error) {
        this.$message.error(error.response.data.message || '创建失败')
      } finally {
        this.loading = false
      }
    },

    async editeVisitorRule(data) {
      this.loading = true
      try {
        const res = await editVisitorRule(data)
        this.$message.success('修改成功')
        setTimeout(() => {
          this.back()
        }, 1000)
      } catch (error) {
        this.$message.error(error.response.data.message || '修改失败')
      } finally {
        this.loading = false
      }
    },

    paramsFormatter() {
      const { ruleId, ruleDetailsForm, noticeForm } = this.formData
      return {
        ruleId,
        content: JSON.stringify(noticeForm.content),
        ruleDetails: JSON.stringify(ruleDetailsForm.content)
      }
    },

    back() {
      this.$router.back()
    },

    async getRuleDetails() {
      try {
        const res = await getVisitorRuleList({ ruleId: this.formData.ruleId })
        const { content, rule_details } = res.data
        this.formData.noticeForm.content = content
        this.formData.ruleDetailsForm.content = rule_details
      } catch (error) {
        this.$message.error(error.response.data.message || '详情获取失败')
      }
    }

  }
}
</script>
<style lang="scss" scoped>
* {
  font-family: HONOR Sans CN, HONOR Sans CN;
}
.rule-details {
  display: flex;
  &__preview {
    //width: 45%;
    padding: 75px 173px;
  }

  &__fill {
    padding: 20px;
    flex: 1;

    .card {
      padding: 20px;
      margin-bottom: 20px;
      background-color: #fff;
      border-radius: 4px;
    }

    .button-group {
      display: flex;
      justify-content: space-between;
      .button {
        cursor: pointer;
        padding: 7px 16px;
        border-radius: 4px;
        margin-right: 20px;
        font-size: 14px;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        transition: all .3s;
        &:last-child {
          margin-right: 0;
        }
        .icon {
          margin-right: 8px;
        }

        &--plain {
          color: #1890ff;
          border: 1px solid #1890ff;
          &:hover {
            background-color: #ECF5FF;
          }
        }

        &--primary {
          background-color: #1890ff;
          color: #fff;
          opacity: 1;
          &:hover {
            opacity: .8;
          }
        }
      }
      &__box {
        display: flex;
      }
    }

    .content-warp {
      height: 732px;
      overflow-y: auto;

      &::-webkit-scrollbar {
        display: none;
      }

      .title {
        font-weight: 700;
        color: #303133;
        font-size: 18px;
        margin-bottom: 16px;
      }

      .form-item__box {
        padding: 20px;
        background-color: #F5F7FA;
        border-radius: 4px;
        position: relative;
        margin-bottom: 16px;
        &:last-child {
          margin-bottom: 0;
        }

        .form-label {
          color: #303133;
          font-size: 14px;
          font-weight: 400;
        }

        .close-icon {
          position: absolute;
          right: 20px;
          font-size: 24px;
          color: #303133;
          z-index: 3;
        }
      }

    }
  }
}

::v-deep(.el-form-item__label) {
  padding: 0 16px 0 0;
}

::v-deep(.el-upload--picture-card) {
  width: 96px;
  height: 96px;
  line-height: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

::v-deep(.el-form-item__content) {
  line-height: 40px;
}

.avatar-uploader {
  margin-top: 10px;
}
</style>
